package com.blog.cloud.service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.blog.cloud.api.dto.UserInfoDto;
import com.blog.cloud.api.dto.UserRegisterDto;
import com.blog.cloud.api.entity.User;
import com.blog.cloud.cache.constants.CacheConstant;
import com.blog.cloud.core.exception.BlogException;
import com.blog.cloud.core.utils.BeanCopyUtil;
import com.blog.cloud.service.mapper.UserMapper;
import com.blog.cloud.service.service.UserRoleService;
import com.blog.cloud.service.service.UserService;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;
import java.util.Set;

/**
 * 用户表(User)表服务实现类
 *
 * @author 龙茶清欢
 * @since 2023-02-26 18:48:26
 */
@CacheConfig(cacheNames = CacheConstant.USER_DETAIL)
@Service("userService")
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    private UserRoleService userRoleService;

    @CachePut(cacheNames = CacheConstant.USER_DETAIL, key = "#username")
    @Override
    public UserInfoDto findUserByUsername(String username) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, username);
        User user = this.baseMapper.selectOne(wrapper);
        if (Objects.isNull(user)) {
            throw new BlogException("用户不存在");
        }

        // 根据userId连表查询用户角色名称
        Set<String> roleNames = this.baseMapper.getRoleNameByUserId(user.getUserId());
        return new UserInfoDto().setUser(user).setRoles(roleNames);
    }

    @CachePut(cacheNames = CacheConstant.USER_DETAIL, key = "#mobile")
    @Override
    public UserInfoDto findUserByMobile(String mobile) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getMobile, mobile);
        User user = this.baseMapper.selectOne(wrapper);
        if (Objects.isNull(user)) {
            throw new BlogException("用户不存在");
        }

        // 根据userId连表查询用户角色名称
        Set<String> roleNames = this.baseMapper.getRoleNameByUserId(user.getUserId());
        return new UserInfoDto().setUser(user).setRoles(roleNames);
    }

    @Override
    public User findUserByFlag(UserRegisterDto registerDto) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getUsername, registerDto.getUsername()).or().eq(User::getMobile, registerDto.getMobile());
        return this.baseMapper.selectOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveUser(UserRegisterDto registerDto) {
        User user = BeanCopyUtil.singleCopy(registerDto, User.class);
        int result = this.baseMapper.insert(user);
        return result == 1;
    }
}

